import connector
import dao.UserDao
# QtCore包含了核心的事件循环、信号和槽机制、线程等核心功能；
# QtGui提供了用于创建图形用户界面的基本元素和工具；
# QtWidgets则包含了各种常用的控件和小部件，如按钮、标签、文本框等
from PyQt5 import QtCore, QtGui, QtWidgets
# QMainWindow是Qt GUI编程中的一种窗口类，用于创建主窗口，提供基本的窗口功能
from PyQt5.Qt import QMainWindow
# QMessageBox是Qt GUI库中的一个类，用于创建消息框，可以用来向用户显示信息、警告或错误消息
from PyQt5.QtWidgets import QMessageBox
from pages.ManagementPage import ManagementPage
from pages.RegisterPage import RegisterPage
from pages.TicketSearchPage import TicketSearchPage
from tools import MessageBoxTools


class LoginPage(QMainWindow):
    def __init__(self):
        super().__init__()
        # self.register_page = None
        # 调用QMainWindow父类当中的init方法
        self.setupUi()
        # 我们如果想要显示出界面，需要调用show()
        self.show()
        self.driver = connector.driver.DatabaseDriver()

    def setupUi(self):
        self.setObjectName("MainWindow")
        self.resize(845, 538)
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(60, 40, 731, 111))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(48)
        self.label.setFont(font)
        self.label.setStyleSheet("")
        self.label.setObjectName("label")
        self.username_edit = QtWidgets.QLineEdit(self.centralwidget)
        self.username_edit.setGeometry(QtCore.QRect(430, 170, 311, 51))
        self.username_edit.setObjectName("username_edit")
        self.password_edit = QtWidgets.QLineEdit(self.centralwidget)
        self.password_edit.setGeometry(QtCore.QRect(430, 250, 311, 51))
        self.password_edit.setObjectName("password_edit")
        self.login_btn = QtWidgets.QPushButton(self.centralwidget)
        self.login_btn.setGeometry(QtCore.QRect(460, 360, 191, 41))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.login_btn.setFont(font)
        self.login_btn.setObjectName("login_btn")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(350, 170, 61, 51))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(350, 250, 61, 51))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("")
        self.label_3.setObjectName("label_3")
        self.register_btn = QtWidgets.QPushButton(self.centralwidget)
        self.register_btn.setGeometry(QtCore.QRect(430, 310, 241, 51))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.register_btn.setFont(font)
        self.register_btn.setStyleSheet("background-color: rgba(255, 255, 255, 0);")
        self.register_btn.setObjectName("register_btn")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(70, 160, 271, 241))
        self.label_4.setStyleSheet("border-image: url(view/img/a.jpg);")
        self.label_4.setText("")
        self.label_4.setObjectName("label_4")
        self.label_4.raise_()
        self.label.raise_()
        self.username_edit.raise_()
        self.password_edit.raise_()
        self.login_btn.raise_()
        self.label_2.raise_()
        self.label_3.raise_()
        self.register_btn.raise_()
        self.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 845, 26))
        self.menubar.setObjectName("menubar")
        self.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

        self.connect_bind()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "高铁火车票查询系统"))
        self.label.setText(_translate("MainWindow", "高铁火车票查询系统"))
        self.username_edit.setPlaceholderText(_translate("MainWindow", "请输入账户"))
        self.password_edit.setPlaceholderText(_translate("MainWindow", "请输入密码"))
        self.login_btn.setText(_translate("MainWindow", "登录"))
        self.label_2.setText(_translate("MainWindow", "账号："))
        self.label_3.setText(_translate("MainWindow", "密码："))
        self.register_btn.setText(_translate("MainWindow", "没有账户？请注册"))

    # 事件绑定关联
    def connect_bind(self):
        self.login_btn.clicked.connect(self.login_btn_clicked)
        self.register_btn.clicked.connect(self.register_btn_cilcked)

    # 登录按钮点击事件
    def login_btn_clicked(self):
        # 首先判断用户名和密码是否为空
        if self.username_edit.text() == "" or self.password_edit.text() == "":
            MessageBoxTools.warning(title='输入错误', text="请输入用户名和密码！")
        else:
            # 字符长度不会引起崩溃
            # 添加字符判断
            # isalnum()：检查字符串是否由字母和数字组成
            if not self.username_edit.text().isalnum() or not self.password_edit.text().isalnum():
                MessageBoxTools.warning(title='输入错误', text="用户名,密码只能包含字母和数字！")
                return
            # 说明用户输入了账户和密码
            result: tuple = dao.UserDao.login(self.driver, self.username_edit.text(), self.password_edit.text())

            # result[0] 用户id result[1] 用户角色
            # 如果查询到用户信息，则返回一个元组，否则返回None
            if result is not None and len(result) == 2:
                if result[1] == '0':
                    # 表明是管理员
                    MessageBoxTools.information(title='登录成功', text="欢迎管理员：" + self.username_edit.text(),
                                                buttons=QMessageBox.Ok)
                    # 启动管理员界面
                    self.ManagementPage = ManagementPage()

                else:
                    # 表明是普通用户
                    MessageBoxTools.information(title='登录成功', text="欢迎用户：" + self.username_edit.text(),
                                                buttons=QMessageBox.Ok)
                    # 启动用户界面
                    self.TicketSearchPage = TicketSearchPage()
                # 关闭当前窗口
                self.close()
            else:
                MessageBoxTools.warning(title='警告', text="用户名或密码错误！", buttons=QMessageBox.Ok)

    # 注册按钮点击事件
    def register_btn_cilcked(self):
        # 跳转注册页面
        # self.register_page = RegisterPage() 如果不把窗体变为自身属性会出现问题
        self.register_page = RegisterPage()
        self.close()

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.driver.close()

    def keyPressEvent(self, key: QtGui.QKeyEvent) -> None:
        if key.key() == 1677720:
            # 判断按下的是否是回车键
            self.login_btn_clicked()
